package com.sgb.kjwl.view.ui.activity.house;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.amap.api.maps.model.LatLng;
import com.sgb.alimaplibrary.MarkerEntity;
import com.sgb.alimaplibrary.widget.MapMarkerView;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentLeaseHallMapBinding;
import com.sgb.kjwl.di.machine.DaggerMachineFragComponent;
import com.sgb.kjwl.di.machine.MachineFragModule;
import com.sgb.kjwl.model.entity.lease.LeaseMapEntity;
import com.sgb.kjwl.model.entity.request.LeaseHallMapFilterJson;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.view.widget.DictWindow5;
import com.sgb.kjwl.view.widget.MapInfoDialog5;
import com.sgb.kjwl.view.widget.ThreeLevelAreaWindow;
import com.sgb.kjwl.viewmodel.house.LeaseHallMapFragModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * 地图查找Fragment
 */
@Deprecated
public class LeaseHallMapFragment extends AppLazyFragment {
    @Inject
    LeaseHallMapFragModel viewModel;
    private FragmentLeaseHallMapBinding binding;
    private List<String> cityList = new ArrayList<>();
    private ThreeLevelAreaWindow mAddressPop;
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;//省市区
    private List<DictEntity3> typeDictEntityList;//分类
    private DictWindow5 classifyWindow;//分类
    private DictWindow5 brandlWindow5;//类型
    private List<DictEntity3> brandDictEntityList;//类型
    private String categoryParentId = "";
    private String type = "1";
    private String provinceName = "";
    private String cityName = "";
    private List<LeaseMapEntity> bundles = new ArrayList<>();
    private LeaseHallMapFilterJson filterJson = new LeaseHallMapFilterJson();
    private Bundle savedInstanceState;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        this.savedInstanceState = savedInstanceState;
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerMachineFragComponent.builder()
                .appComponent(appComponent)
                .machineFragModule(new MachineFragModule(this))
                .build()
                .inject(this);
    }

    public static LeaseHallMapFragment newInstance(String type) {
        LeaseHallMapFragment fragment = new LeaseHallMapFragment();
        Bundle bundle = new Bundle();
        bundle.putString("type", type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_lease_hall_map, container, false);
        return binding.getRoot();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        checkDismiss(0);
    }

    @Override
    protected void initView() {
        binding.classifyLayout.setOnClickListener(this);
        binding.typeLayout.setOnClickListener(this);
        binding.areaLayout.setOnClickListener(this);
        initFilterView();
    }

    @Override
    protected void onLazyLoad() {
        if ("3".equals(type)) {
            binding.tvClassify.setText("车型");
            binding.tvType.setText("品牌");
        } else if ("6".equals(type)) {//工厂没有类型,需隐藏
            binding.typeLayout.setVisibility(View.GONE);
        }
        provinceName = viewModel.getAreaNameModel();
        filterJson.setProvinceNo(viewModel.getAreaCodeModel());
        viewModel.getFilterTypeModel(type);
        initMap(savedInstanceState);
    }

    /**
     *
     */
    private void initFilterView() {
        //分类选择
        classifyWindow = new DictWindow5(getActivity());
        classifyWindow.setFocusable(false);
        classifyWindow.setOutsideTouchable(false);
        classifyWindow.setOnCallBack(new DictWindow5.OnCallBack() {
            @Override
            public void result(DictEntity3 dictEntity) {
                updateChooseTextStatus(binding.classifyLayout, binding.tvClassify, 2, dictEntity.getName());
                if (!"3".equals(type)) {
                    //重置类型
                    if (brandDictEntityList != null && brandDictEntityList.size() > 0) {
                        brandlWindow5.setCheckDefaultById(brandDictEntityList.get(0).getId());
                        filterJson.setSecondCategory(brandDictEntityList.get(0).getId());
                    }
                }

                //设置筛选结果
                categoryParentId = dictEntity.getId();
                filterJson.setFirstCategory(dictEntity.getId());
                getAllList();
            }
        });
        classifyWindow.setOnCloseBack(new DictWindow5.OnCloseBack() {
            @Override
            public void dismiss() {
                if ("分类".equals(binding.tvClassify.getText()) || "车型".equals(binding.tvClassify.getText())) {
                    updateChooseTextStatus(binding.classifyLayout, binding.tvClassify, 0, null);
                } else {
                    updateChooseTextStatus(binding.classifyLayout, binding.tvClassify, 2, null);
                }
            }
        });

        //类型选择
        brandlWindow5 = new DictWindow5(getActivity());
        brandlWindow5.setFocusable(false);
        brandlWindow5.setOutsideTouchable(false);
        brandlWindow5.setOnCallBack(new DictWindow5.OnCallBack() {
            @Override
            public void result(DictEntity3 dictEntity) {
                updateChooseTextStatus(binding.typeLayout, binding.tvType, 2, dictEntity.getName());
                filterJson.setSecondCategory(dictEntity.getId());
                getAllList();
            }
        });
        brandlWindow5.setOnCloseBack(new DictWindow5.OnCloseBack() {
            @Override
            public void dismiss() {
                if ("类型".equals(binding.tvType.getText()) || "品牌".equals(binding.tvType.getText())) {
                    updateChooseTextStatus(binding.typeLayout, binding.tvType, 0, null);
                } else {
                    updateChooseTextStatus(binding.typeLayout, binding.tvType, 2, null);
                }
            }
        });

        mAddressPop = new ThreeLevelAreaWindow(getActivity());
        mAddressPop.setBgView(binding.grayLayout);
        mAddressPop.setMemberHeight();
        mAddressPop.setProvinceSingle();
        mAddressPop.setCitySingle();
        mAddressPop.setAreaMore();
        mAddressPop.setShowSimpleName(true);
        mAddressPop.setOnResultClick((key1, key2, key3) -> {
            try {
                List<BaseAreaEntity> listKey1 = (List<BaseAreaEntity>) key1;
                List<BaseAreaEntity> listKey2 = (List<BaseAreaEntity>) key2;
                List<BaseAreaEntity> listKey3 = (List<BaseAreaEntity>) key3;
                filterJson.setAreaNos(getCityList(listKey3)); //获取区多选列表
                if (listKey2 != null && listKey2.size() > 0) {
                    cityName = listKey2.get(0).getName();
                    filterJson.setCityNo(listKey2.get(0).getNo());
                } else {
                    filterJson.setCityNo("");
                }
                filterJson.setProvinceNo(listKey1.get(0).getNo());
                provinceName = listKey1.get(0).getName();
            } catch (Exception exception) {
            }

            getAllList();
            if (!TextUtils.isEmpty(cityName) && "不限".equals(cityName)) {
                updateChooseTextStatus(binding.areaLayout, binding.tvArea, 2, cityName);
            } else {
                updateChooseTextStatus(binding.areaLayout, binding.tvArea, 2, provinceName);
            }

        });
        mAddressPop.setOnDismissListener(() -> {
            updateChooseTextStatus(binding.areaLayout, binding.tvArea, "地区".equals(binding.tvArea.getText()) ? 0 : 2, null);
        });

    }

    private List<String> getCityList(List<BaseAreaEntity> list) {
        cityList = new ArrayList<>();
        for (BaseAreaEntity entity : list) {
            if (!TextUtils.isEmpty(entity.getNo())) {
                cityList.add(entity.getNo());
            }
        }
        return cityList;
    }


    private void getAllList() {
        viewModel.getLeaseMapSearch(filterJson, false);
    }

    @Override
    public void setArguments(@Nullable Bundle args) {
        super.setArguments(args);
        if (args != null) {
            type = args.getString("type", "1");
            filterJson.setType(type);
        }
    }

    //初始化地图
    private void initMap(Bundle savedInstanceState) {
        binding.mMapView.initMap(savedInstanceState, getLifecycle(), 10, new MapMarkerView.CallBack() {
            @Override
            public void onMarkerClick(int pos, String title) {
                showMarkerView(pos, title);
            }

            @Override
            public void onLocation(Double Lat, Double Log, String string) {
                if (!TextUtils.isEmpty(filterJson.getLatitude()) && !"0.0".equals(filterJson.getLongitude()))
                    return;
                filterJson.setLatitude(Lat);
                filterJson.setLongitude(Log);
                getAllList();
            }

        });
    }

    //展示地图覆盖物
    private void showMarkerView(int pos, String title) {
        LeaseMapEntity data = bundles.get(pos);
//        new MapInfoDialog5(getActivity(), null)
//                .setCallBackListener(new MapInfoDialog5.CallBackListener() {
//                    @Override
//                    public void onClickShop(LeaseMapEntity entity) {
//                        if ("7".equals(type)) {
//                            viewModel.getH5Url(Integer.parseInt(type), entity.getNo());
//                        } else {
//                            viewModel.getH5Url(Integer.parseInt(type), entity.getDataId());
//                        }
//                    }
//                })
//                .setData(data);
    }

    public void showMapMark(List<LeaseMapEntity> list) {
        if (list == null || list.size() == 0) {
            return;
        }
        addMarkInfoWindow(list);
    }

    private void addMarkInfoWindow(List<LeaseMapEntity> datas) {
        try {
            bundles.clear();
            List<MarkerEntity> markerEntityList = new ArrayList<>();
            for (int i = 0; i < datas.size(); i++) {
                LeaseMapEntity entity = datas.get(i);
                if (checkItude(entity.getLongitude(), entity.getLatitude())) {
                    LatLng latLng = new LatLng(Double.parseDouble(entity.getLatitude()), Double.parseDouble(entity.getLongitude()));
                    int icon = R.mipmap.ic_map_overlay_machine;
                    if ("1".equals(type)) {
                        icon = R.mipmap.ic_map_overlay_machine;
                    } else if ("2".equals(type)) {
                        icon = R.mipmap.ic_map_overlay_device;
                    } else if ("3".equals(type)) {
                        icon = R.mipmap.ic_map_overlay_car;
                    } else if ("4".equals(type)) {
                        icon = R.mipmap.ic_map_overlay_house;
                    } else if ("5".equals(type)) {
                        icon = R.mipmap.ic_map_overlay_land;
                    } else if ("6".equals(type)) {
                        icon = R.mipmap.ic_map_overlay_factory;
                    } else if ("7".equals(type)) {
                        icon = R.mipmap.ic_map_overlay_farm;
                    }
                    markerEntityList.add(new MarkerEntity(latLng, icon, entity.getNo()));
                    bundles.add(entity);
                }
            }
            binding.mMapView.setMarkerData(markerEntityList);
            binding.mMapView.zoomToSpan(markerEntityList.get(0).getLatLng());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //设置一级分类数据
    public void showTypePopWindow(List<DictEntity3> data) {
        this.typeDictEntityList = data;
        if (data == null) {
            data = new ArrayList<>();
        }
        categoryParentId = filterJson.getFirstCategory();
        if (TextUtils.isEmpty(categoryParentId)) {
            categoryParentId = data.get(0).getId();
        }
        classifyWindow.setData(data);
        classifyWindow.setCheckDefaultById(categoryParentId);
        filterJson.setFirstCategory(categoryParentId);
    }

    //设置二级分类数据
    public void showBrandPopWindow(List<DictEntity3> data) {
        this.brandDictEntityList = data;
        if (data == null) {
            data = new ArrayList<>();
        }
        String defaultId = filterJson.getSecondCategory();
        if (TextUtils.isEmpty(defaultId)) {
            defaultId = "";
        }
        brandlWindow5.setData(data);
        brandlWindow5.setCheckDefaultById(defaultId);
        filterJson.setSecondCategory(defaultId);
    }

    public void showAddressDatas(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data, String provinceNo) {
        if (data != null && data.size() > 0) {
            addressEntityList = data;
            filterJson.setProvinceNo(provinceNo);
            mAddressPop.setData(data, true, provinceNo);
        }
    }

    @Override
    public void onClick(View v) {
        checkDismiss(v.getId());
        switch (v.getId()) {
            case R.id.classify_layout://分类
                if ("分类".equals(binding.tvClassify.getText()) || "车型".equals(binding.tvClassify.getText())) {
                    updateChooseTextStatus(binding.classifyLayout, binding.tvClassify, -1, null);
                } else {
                    updateChooseTextStatus(binding.classifyLayout, binding.tvClassify, 1, null);
                }
                classifyWindow.setCheckDefaultById(filterJson.getFirstCategory());
                classifyWindow.showPopwindow(binding.classifyLayout);
                if (typeDictEntityList == null) {
                    viewModel.getFilterTypeModel(type);
                }
                break;
            case R.id.type_layout://类型
                if ("类型".equals(binding.tvType.getText()) || "品牌".equals(binding.tvType.getText())) {
                    updateChooseTextStatus(binding.typeLayout, binding.tvType, -1, null);
                } else {
                    updateChooseTextStatus(binding.typeLayout, binding.tvType, 1, null);
                }
                brandlWindow5.setCheckDefaultById(filterJson.getSecondCategory());
                brandlWindow5.showPopwindow(binding.typeLayout);
                viewModel.getFilterModelModel(type, categoryParentId);
                break;
            case R.id.area_layout://地区
                updateChooseTextStatus(binding.areaLayout, binding.tvArea, "地区".equals(binding.tvArea.getText()) ? -1 : 1, null);
                mAddressPop.showPopwindow(binding.areaLayout);
                if (addressEntityList == null) {
                    viewModel.getCityData();
                }
                break;
        }
    }

    private void checkDismiss(int rid) {
        if (rid != R.id.classify_layout && classifyWindow != null && classifyWindow.isShowing()) {
            classifyWindow.dismiss();
        }
        if (rid != R.id.type_layout && classifyWindow != null && brandlWindow5.isShowing()) {
            brandlWindow5.dismiss();
        }
        if (rid != R.id.area_layout && classifyWindow != null && mAddressPop.isShowing()) {
            mAddressPop.dismiss();
        }
    }

    //更新选项颜色
    private void updateChooseTextStatus(View view, TextView textView, int value, String name) {
        if (!TextUtils.isEmpty(name)) {
            textView.setText(name);
        }
        if (value == 0) {
            setTextViewBg(view, textView, R.drawable.search_bg, R.mipmap.ic_down_arrow_n, R.color.color_333333);
        } else if (value == -1) {
            setTextViewBg(view, textView, R.drawable.search_bg, R.mipmap.ic_up_arrow_n, R.color.color_333333);
        } else if (value == 1) {
            setTextViewBg(view, textView, R.drawable.search_new_blue_bg, R.mipmap.icon_up_red, R.color.color_main);
        } else if (value == 2) {
            setTextViewBg(view, textView, R.drawable.search_new_blue_bg, R.mipmap.icon_down_red, R.color.color_main);
        }
    }

    //设置背景色和图标
    private void setTextViewBg(View view, TextView textView, int bg, int img, int textColor) {
        view.setBackgroundResource(bg);
        Drawable drawable_n = getResources().getDrawable(img);
        drawable_n.setBounds(0, 0, drawable_n.getMinimumWidth(), drawable_n.getMinimumHeight());
        textView.setCompoundDrawables(null, null, drawable_n, null);
        textView.setTextColor(getResources().getColor(textColor));
    }


    /**
     * 经纬度校验(只校验正数 0-90.000000 0-180.000000 范围内)
     * 经度longitude: (?:[0-9]|[1-9][0-9]|1[0-7][0-9]|180)\\.([0-9]{6})
     * 纬度latitude：  (?:[0-9]|[1-8][0-9]|90)\\.([0-9]{6})
     *
     * @return
     */
    public static boolean checkItude(String longitude, String latitude) {
        if (TextUtils.isEmpty(longitude) || TextUtils.isEmpty(latitude)) {
            return false;
        }

        try {
            //判断经纬度中国境内正确范围
            if (Double.parseDouble(longitude) > 72.8041 && Double.parseDouble(longitude) < 137.8347) {
                return Double.parseDouble(latitude) > 3.5182 && Double.parseDouble(latitude) < 53.8271;
            } else {
                return false;
            }
        } catch (Exception ex) {
            return false;
        }

    }


}
